package co.edu.unal.satacredito.administration.view.user;

import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import co.edu.unal.satacredito.administration.view.general.AdministrationBean;
import co.edu.unal.satacredito.infrastructure.dto.UserDTO;
import co.edu.unal.satacredito.mediation.UserEJBLocal;

@ManagedBean(name = "editUser")
public class EditUser extends AdministrationBean {

	@EJB
	UserEJBLocal userEJB;
	
	private String user;
	private UserDTO userDTO;
	
	@PostConstruct
	public void init() {
		if (userDTO == null) {
			userDTO = new UserDTO();
		}
	}
	
	public String loadCreate(){
		userDTO.setId(null);
		return SUCCESS;
	}

	public String loadEdit() {
		Map<String, String> params = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap();
		
		user = params.get("p_user");
		userDTO.setUser(user);
		try {
			userDTO = userEJB.findUser(user);
			return SUCCESS;
			
		} catch (Exception e) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"Lo sentimos ocurrio un error inesperado"));
			return FAILED;
		}
	}

	public String doCreate(){
		try {
			userEJB.create(userDTO);
			
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"Nuevo usuario creado"));
			
			return SUCCESS;
			
		} catch (Exception e) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"Error al crear el usuario"));
			
			return FAILED;
		}
		
	}

	public String doEdit() {
		try {
			userEJB.edit(userDTO.getId(),userDTO);
			
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"Actualización finalizada"));
			return SUCCESS;
			
		} catch (Exception e) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"El usuario no se pudo actualizar"));
			return FAILED;
		}
	}
	
	public String doDelete(){
		try {
			
			userEJB.delete(userDTO.getId());
			
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"El usuario a sido borrado"));
			return SUCCESS;
			
		} catch (Exception e) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"No se pudo borrar el usuario"));
			return FAILED;
		}
	}
	
	public String cancel(){
		return SUCCESS;
	}
	
	public UserDTO getUserDTO() {
		return userDTO;
	}

}
